/*
 * To change this template, choose Tools | Templates and open the template in the editor.
 */

package com.cqq.pro.down;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cqq.pro.util.PropertiesUtil;

/**
 * 
 * @author wangjie
 */
@Controller
@RequestMapping(value = "imagePage")
public class ImagePageController {
	Logger logger = Logger.getLogger(ImagePageController.class);

	@RequestMapping(value = "imagePageActivate")
	void onActivate(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String name = request.getParameter("name");
		String dir = request.getParameter("dir");
		String FEEDBACK_PICTURES_SAVE_PATH = PropertiesUtil.getConfigValue("file_path");

		File file = null;
		InputStream is = null;
		try {
			
			file = new File(FEEDBACK_PICTURES_SAVE_PATH +getFilePath(dir)+ name);
			if (null != file) {
				is = new FileInputStream(file);
			}
		} catch (FileNotFoundException ex) {
			logger.error("ImagePage Error: " + ex);
		}
		download(response, is, name.substring(0, name.lastIndexOf(".")));
	}
	
	
	private String getFilePath(String dir){
		if(dir==null||dir.trim().equals(""))
			dir="";
		else if(dir.indexOf("/")<0)
			dir = dir + "/";
		return dir;
	}
	
	public static void download(HttpServletResponse response, InputStream io, String name) throws Exception {
		response.setHeader("content-type", "application/octet-stream");
		response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));
		if (io != null) {
			response.setContentLength(io.available());
		}
		BufferedInputStream in = null;
		BufferedOutputStream out = null;
		try {
			in = new BufferedInputStream(io);
			out = new BufferedOutputStream(response.getOutputStream());
			for (int data = 0; (data = in.read()) != -1;) {
				out.write(data);
			}
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

}
